package main

import (
	"encoding/json"
	"fmt"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
	"strconv"
)

type StudentChaincode struct {

}

type Student struct {
	Name string
	Math int
	Chinese int
	Total int
}

func (t *StudentChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
	return shim.Success(nil)
}

func (t *StudentChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	_, args = stub.GetFunctionAndParameters()

	fmt.Println("This txid is " + stub.GetTxID())
	fmt.Println("This channelid is " + stub.GetChannelID())

	name := args[0]
	math, err := strconv.Atoi(args[1])
	if err != nil {
		return shim.Error(err.Error())
	}
	chinese, err := strconv.Atoi(args[2])
	if err != nil {
		return shim.Error(err.Error())
	}
	total := (math + chinese) / 2

	student := Student{
	name,
	math,
	chinese,
	total,
	}
	data, err := json.Marshal(student)
	if err != nil {
		return shim.Error(err.Error())
	}

	err = stub.PutState(name, []byte(data))
	if err != nil {
		return shim.Error(err.Error())
	}
	return shim.Success(nil)
}

func (t *StudentChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	_, args = stub.GetFunctionAndParameters()
	name := args[0]
	data, err := stub.GetState(name)
	if err != nil {
		return shim.Error(err.Error())
	}

	student := Student{}
	err = json.Unmarshal(data, &student)
	if err != nil {
		return shim.Error(err.Error())
	}
	fmt.Printf("The %s math core is %d, chinese core is %d, total is %d\n", name, student.Math, student.Chinese, student.Total)

	return shim.Success([]byte(strconv.Itoa(student.Total)))
}

func (t *StudentChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
	function, args := stub.GetFunctionAndParameters()
	if function == "invoke" {
		return t.invoke(stub, args)
	} else if function == "query" {
		return t.query(stub, args)
	} else {
		return shim.Error("Haven't function")
	}
}

func main() {
	err := shim.Start(new(StudentChaincode))
	if err != nil {
		fmt.Printf("error: %s", err.Error())
	}
}